package com.lsp.java.dataStructure.linked;

/**
 * @description: 单链表：数据和指向下一个节点的指针
 * @author: Lisp
 * @time: 2020/9/3 10:44
 */
public class MyLinkedList {
    private ListNode head;
    private int size = 0;

    //插入头部, data 是插入的数据
    public void insertHead(int data) {
        ListNode newNode = new ListNode(data);
        //如果原来就有数据呢？
        newNode.next = head;
        head = newNode;
    }

    //插入链表的中间
    public void insertNth(int data, int position) {
        if (position == 0) {
            insertHead(data);
        } else {
            ListNode cur = head;
            for (int i = 0; i < position; i++) {
                cur = cur.next;
            }
            ListNode newNode = new ListNode(data);
            //保证原先的后序结点的值不变，先把原先的结点值赋值给新加结点
            newNode.next = cur.next;
            //新加结点作为原先结点的 next
            cur.next = newNode;
        }
    }

    //删除头结点
    public void deleteHead() {
        head = head.next;//不能用 head = null;这样会造成结点数据丢失
    }

    //删除指定位置的结点
    public void deleteNth(int position) {
        if (position == 0) {
            deleteHead();
        } else {
            ListNode cur = head;
            for (int i = 0; i < position; i++) {
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
    }

    //打印 list 的值
    public void print() {
        ListNode cur = head;
        while (cur != null) {
            System.out.println(cur.value + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    //查找某个值
    public void find(int data) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.value == data) break;
            cur = cur.next;
        }
    }
}

class ListNode {
    int value;//值
    ListNode next; //下一个指针

    public ListNode(int value) {
        this.value = value;
        this.next = null;//最开始的时候下一个结点为 null
    }

}
